package com.java8.stream;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 终止操作
 */
public class TestStreamAPI3 {
    /**
     * 查找与匹配
     * allMatch--检查是否匹配所有元素
     * anyMatch--检查是否至少匹配一个元素
     * noneMatch -- 检查是否没有匹配所有元素
     * findFirst--返回当前流中的任意元素
     * count--返回流中元素总个数
     * max--返回流中最大值
     * min--返回流中最小值
     */
    List<EmployeeVO> employeeVOS = Arrays.asList(
            new EmployeeVO("张三", 18, 9999.99, EmployeeVO.Status.BUSY),
            new EmployeeVO("李四", 22, 5555.55, EmployeeVO.Status.BUSY)
    );

    @Test
    public void test1() {
        boolean allMatch = employeeVOS.stream().allMatch(employeeVO -> employeeVO.getStatus().equals(EmployeeVO.Status.BUSY));
        System.out.println(allMatch);

        boolean anyMatch = employeeVOS.stream().anyMatch(employeeVO -> employeeVO.getStatus().equals(EmployeeVO.Status.BUSY));
        System.out.println(anyMatch);

        boolean noneMatch = employeeVOS.stream().noneMatch(employeeVO -> employeeVO.getStatus().equals(EmployeeVO.Status.BUSY));
        System.out.println(noneMatch);

        //Optional容器类
        Optional<EmployeeVO> first = employeeVOS.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();
        EmployeeVO employeeVO = first.get();
        System.out.println(employeeVO);

        Optional<EmployeeVO> any = employeeVOS.stream().findAny();
        EmployeeVO employeeVO1 = any.orElse(new EmployeeVO());
        EmployeeVO employeeVO2 = any.get();
        System.out.println(employeeVO1);
        System.out.println(employeeVO2);


    }


    /**
     * 串行:  一个完完整整的执行完了再执行下一个.
     * 并发:  看起来是同时运行的
     * 并行:  真正做到了同时运行
     * <p>
     * 多道技术(了解):
     * 空间复用: 共用一个内存条,每一个进程都有自己独立的内存空间,互不干扰,物理级别的隔离.
     * 时间复用: 共用了一个cpu
     * cpu切换(掌握):
     * io的时候,占用时间过长切换,
     * <p>
     * <p>
     * #三 现代计算机：
     * 现在的主机一般是多核，那么每个核都会利用多道技术
     * 有4个cpu，运行于cpu1的某个程序遇到io阻塞，会等到io结束再重新调度，会被调度到4个
     * cpu中的任意一个，具体由操作系统调度算法决定。
     */

    @Test
    public void test2() {
        //stream是串行流，parallelStream是并行流,并行流会去找空闲
        Optional<EmployeeVO> any = employeeVOS.parallelStream().filter(employeeVO -> employeeVO.getStatus().equals(EmployeeVO.Status.BUSY)).findAny();
        EmployeeVO employeeVO = any.get();
        System.out.println(employeeVO);
    }

    @Test
    public void test3() {
        long count = employeeVOS.parallelStream().count();
        System.out.println(count);

        Optional<EmployeeVO> max = employeeVOS.parallelStream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        EmployeeVO employeeVO = max.get();
        System.out.println(employeeVO);
        Optional<Double> min = employeeVOS.parallelStream().map(EmployeeVO::getSalary).min(Double::compareTo);
        Double aDouble = min.get();
        System.out.println(aDouble);
    }
}
